package com.cci.kangdao.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.dao.DictionariesTDao;
import com.cci.kangdao.dao.IntegralOperationDao;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.model.IntegralSetupT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dto.response.MedbFleet;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.IntegralOperationService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 积分相关操作
 */
@Service
public class IntegralOperationServiceImpl implements IntegralOperationService {
	private Logger log = Logger.getLogger(this.getClass().getName());
	@Autowired
	private IntegralOperationDao integralOperationDao;
	@Autowired
	private RedisClientUtils redisClientUtils;

	@Autowired
	private LoginDao loginDao;
	
	@Resource
	private PropertiesUtils propertiesUtils;
	@Value("${cipBehaviorUrl}")
	private String CIP_BEHAVIOR_URL;
	@Resource
	private DictionariesTDao dictionariesTDao;

	private static final String CIPPOINT = "cipPoint";
	/**
	 * App用户获取积分日志接口
	 */
	@Override
	public ModelAndView getIntegralLog(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			// {
			// "status": 0,
			// "msg": "",
			// "integralSetup": [{
			// "integralChannel": "登录",
			// "integralNum": 1,
			// "systime": "2018-04-18 12:12:23"
			// }]
			// }
			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");
			if (userid.equals("")) {
				obj.put("status", -3);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			userid = AESTool.decryptString(userid);// 解密userid
			/**
			 * 根据userid获取user表的id
			 */
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
			map.put("userid", userT.getId());

			int page = 1;
			if (map.get("page") != null) {
				page = MapUtils.getInteger(map, "page", 1);
			}
			int pagesize = Integer.valueOf(this.propertiesUtils.getPropertiesValue("pagesize"));

			obj.put("status", 0);
			obj.put("msg", "");
			JSONObject content;
			JSONArray jsonArray = new JSONArray();
			/**
			 * 查询用户的积分
			 */
			PageHelper.startPage(page, pagesize);
			List<IntegralSetupT> integralLogList = integralOperationDao.getIntegralLog(map);
			// "msg": "",
			// "integralTol": 101,
			// "integralSetup": [{
			// "integralChannel": "登录",
			// "integralNum": 1,
			// "systime": "2018-04-18 12:12:23"
			// }]
			obj.put("integralTol", userT.getIntegral());
			if(integralLogList != null){
				for (IntegralSetupT integralSetupT : integralLogList) {
					content = new JSONObject();
					content.put("integralChannel", integralSetupT.getIntegralChannel());
					content.put("integralNum", integralSetupT.getIntegralNum());
					content.put("systime",
							PublicTool.dateTimeChangeChina(integralSetupT.getSystime().toString().substring(0, 19)));
					jsonArray.put(content);
				}
			}
			obj.put("integralSetup", jsonArray);
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * App用户获取积分规则接口
	 */
	@Override
	public ModelAndView getIntegralSetup(Map<String, Object> map) {
			List<IntegralSetupT> integralSetup = integralOperationDao.getIntegralSetup();
			return new ModelAndView("/integralSetup","model",integralSetup);
	}

	/**
	 * App用户上传行为记录接口
	 */
	@Override
	public ModelAndView uploadRecordLogs(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();
			// actionName 访问功能
			// residenceTime 访问时长（单位秒），可不传
			// IP 访问IP
			// appVersion APP版本号
			// mobileType 手机品牌
			// mobileModel 手机型号
			// systemVersion 安卓/iOS手机系统版本
			/**
			 * 判断传递的参数
			 */
			if (map.get("actionName") == null || map.get("actionName").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}			
			if (map.get("appVersion") == null || map.get("appVersion").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			if (map.get("mobileType") == null || map.get("mobileType").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			if (map.get("systemVersion") == null || map.get("systemVersion").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			if (map.get("residenceTime") == null || map.get("systemVersion").toString().equals("")) {
				map.put("residenceTime", "");
			}
			String  IP = PublicTool.getIp(request);
			map.put("IP",IP);

			/**
			 * 1、查询用户信息
			 */
			String userid = request.getHeader("userid");
			/**
			 * 2.根据userid查询出user表的id如果userid是空代表游客是存入user表的id是0
			 */
			if (userid == null) {// 代表游客
				map.put("userid", 0);
			} else {
				userid = AESTool.decryptString(userid);// 解密userid
				UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);

				if(null == userT) {
					if(!NumberUtils.isDigits(userid)){
						ParameterTool.writeErrorResponse(response,-1);
						return null;
					}
					userT = loginDao.getUserByid(userid);
					if(userT == null){
						obj.put("status", -3);
						obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));

						//返回客户
						ParameterTool.writeResponse(response, obj.toString());
						obj = null;
						return null;
					}
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.setObject("userT"+userT.getId(), userT, redisCacheTime);

				}
				map.put("userid", userT.getId());

			}
			/**
			 * 3.存入行为记录表中
			 */
			map.put("endtime", LocalTimeUtil.getRealCurrentTime());
			String date = LocalTimeUtil.getFormatterRealCurrentTime(LocalTimeUtil.DATE_FORMATTER);
			map.put("date", date);
			int i = integralOperationDao.uploadRecordLogs(map);
			if (i > 0) {
				obj.put("status", 0);
				obj.put("msg", "");
				//同步cip的埋点
				this.syncCipLog(map);
			} else {
				obj.put("status", -99);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
			}
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	//同步cip的行为记录
	public void syncCipLog(Map<String,Object> map){
		ThreadPoolUtil.newTask(new Thread(() -> {

			String actionName = MapUtils.getString(map, "actionName");
			//查询字典项
			String point = dictionariesTDao.getListByDTableName(CIPPOINT);
			if (StringUtils.isNotBlank(actionName) && StringUtils.isNotBlank(point)) {
				List<String> pointList = JSON.parseArray(point, String.class);
				if (CollectionUtils.isNotEmpty(pointList)) {
					if (pointList.stream().anyMatch( e -> e.equals(actionName))|| actionName.contains("C端首页")) {
						com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
						com.alibaba.fastjson.JSONObject childjsonObject = new com.alibaba.fastjson.JSONObject();
						childjsonObject.put("userId", map.get("userid")!=null ? ""+map.get("userid") :"");
						childjsonObject.put("mode", map.get("mode") !=null ? map.get("mode") : "Formal");
						childjsonObject.put("client", "eCummins");
						childjsonObject.put("abnormalStatus", 1);
						childjsonObject.put("action", map.get("actionName"));
						childjsonObject.put("eventTime", LocalTimeUtil.getRealCurrentTime());
						childjsonObject.put("esns", map.get("esns"));
						//childjsonObject.put("connectionStatus",);
						childjsonObject.put("source", 0);
						childjsonObject.put("fleetId", map.get("fleetId"));
						jsonObject.put("app", "FC");
						jsonObject.put("type", "FC_ACTION");
						jsonObject.put("content", childjsonObject);
						String resultStr = HttpUtils.postJson(CIP_BEHAVIOR_URL, jsonObject.toString(), new ResponseHandler<String>() {
							@Override
							public String handleResponse(HttpResponse response)
									throws IOException {
								log.info("获取 CIP_BEHAVIOR_URL ；打印地址：" + CIP_BEHAVIOR_URL+"，参数："+jsonObject.toJSONString() );
								if (response.getStatusLine().getStatusCode() == 200) {
									HttpEntity httpEntity = response.getEntity();
									String str = EntityUtils.toString(httpEntity);
									log.info("获取 CIP_BEHAVIOR_URL成功 ；返回结果：" + str);
									return str;
								}
								log.info("获取 CIP_BEHAVIOR_URL失败 ；返回结果：" + response.toString());
								return null;
							}
						});
					}
				}
			}
		}));
	}

	/**
	 * App用户上传积分接口
	 */
	public ModelAndView uploadIntegral(Map<String, Object> map) {
		try {
			HttpServletResponse response = (HttpServletResponse) map.get("response");
			HttpServletRequest request = (HttpServletRequest) map.get("request");
			JSONObject obj = new JSONObject();

			/**
			 * 判断参数是否为空
			 */
			/*if (map.get("integralSetupID") == null || map.get("integralSetupID").toString().equals("")) {
				obj.put("status", -5);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			// 解密积分规则id
			map.put("integralSetupID", AESTool.decryptString(map.get("integralSetupID").toString()));
			*//**
			 * 1、查询用户信息
			 *//*
			String userid = request.getHeader("userid");
			if (userid == null) {
				obj.put("status", -3);
				obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			userid = AESTool.decryptString(userid);// 解密userid
			// 根据userid查询出user表的id
			UserT userT = (UserT) redisClientUtils.getObject("userT" + userid);
			map.put("userid", userT.getId());
			*//**
			 * 1.根据积分id去积分设置表取对应的积分
			 *//*
			int integralNum = 0;
			Integer dayNum = 0;
			Map<String, IntegralSetupT> IntegralSetupTtMap = getIntegralSetupTRedis();
			if (IntegralSetupTtMap.get(map.get("integralSetupID").toString()) != null) {
				// 获取每次的积分
				integralNum = IntegralSetupTtMap.get(map.get("integralSetupID").toString()).getIntegralNum();
				// 每日获取的次数
				dayNum = IntegralSetupTtMap.get(map.get("integralSetupID").toString()).getDayNum();
			}
			if(dayNum == 0){
				obj.put("msg", "今日可积分次数为0");

				// 返回客户
				ParameterTool.writeResponse(response, obj.toString());
				obj = null;
				return null;
			}
			map.put("dayNum", dayNum);
			map.put("integralNum", integralNum);
			*//**
			 * 2.根据用户名字跟积分表的ID去查询这个有没有数据或者几条
			 *//*
			// 获凌晨时间取时间点
			String startTime = Date_Util.getOnlyDate().trim() + " 00:00:00";
			map.put("startTime", PublicTool.dateTimeChangeUs(startTime).substring(0,19));
			// 获取最后时间
			String endTime = Date_Util.getOnlyDate().trim() + " 23:59:59";
			map.put("endTime", PublicTool.dateTimeChangeUs(endTime).substring(0,19));
			int i = integralOperationDao.getCountIntegralLogT(map);			
			if(i<dayNum){
				*//**
				 * //判断积分次数是否小于积分设置
				 * 3.插入积分日志
				 *//*
				// 去出当前用户的总积分
				int integraCurrent = (int)userT.getIntegral() + integralNum;	
				map.put("integraCurrent", integraCurrent);
				int j = integralOperationDao.insertIntegralLogTDatas(map);
				if (j > 0) {
					*//**
					 * 插入成功后更新user
					 *//*
					userT.setIntegral(integraCurrent);
					int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
					redisClientUtils.delkey("userT"+userid);
					redisClientUtils.setObject("userT"+userid, userT, redisCacheTime);
					
					obj.put("status", 0);
					obj.put("msg", "");
				} else {
					obj.put("status", -99);
					obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));
				}
			}else{
				obj.put("status", 0);
				obj.put("msg", "今日可积分次数为0");
			}*/
			obj.put("status", 0);
			obj.put("msg", "上传失败，接口已作废！");
			ParameterTool.writeResponse(response, obj.toString());
			obj = null;
		} catch (Exception e) {
			// TODO: handle exception
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 从redis中根据积分id取值
	 * 
	 * @return
	 */
	private Map<String, IntegralSetupT> getIntegralSetupTRedis() {

		Map<String, IntegralSetupT> IntegralSetupTtMap = (Map<String, IntegralSetupT>) redisClientUtils
				.getObject("IntegralSetupTtMap");
		if (IntegralSetupTtMap == null) {
			/**
			 * 查询数据库得到积分设置规则
			 */
			List<IntegralSetupT> integralSetupDatas = integralOperationDao.getIntegralSetup();
			if (integralSetupDatas != null && integralSetupDatas.size() > 0) {
				IntegralSetupTtMap = new HashMap<String, IntegralSetupT>();
				for (IntegralSetupT integralSetupT : integralSetupDatas) {
					IntegralSetupTtMap.put("" + integralSetupT.getID(), integralSetupT);
				}
				int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
				redisClientUtils.setObject("IntegralSetupTtMap", IntegralSetupTtMap, redisCacheTime);
			}
		}
		return IntegralSetupTtMap;
	}
}
